<template>
  <PageContainer title="质检记录">
    <!-- 搜索筛选区域 -->
    <SearchForm v-model="searchForm" @search="handleSearch" @reset="handleReset">
      <el-form-item label="质检员">
        <el-select
          v-model="searchForm.inspectorId"
          placeholder="请选择质检员"
          clearable
        >
          <el-option
            v-for="inspector in inspectorOptions"
            :key="inspector.id"
            :label="inspector.name"
            :value="inspector.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="处理结果">
        <el-select
          v-model="searchForm.handleResult"
          placeholder="请选择处理结果"
          clearable
        >
          <el-option label="扣款" value="deduction" />
          <el-option label="补款" value="addition" />
          <el-option label="无需调整" value="no_adjustment" />
        </el-select>
      </el-form-item>
      <el-form-item label="异常类型">
        <el-select
          v-model="searchForm.exceptionType"
          placeholder="请选择异常类型"
          clearable
        >
          <el-option label="重量异常" value="weight_error" />
          <el-option label="分类错误" value="classification_error" />
          <el-option label="图像不符" value="image_mismatch" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </SearchForm>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <StatCard
        :icon="Document"
        icon-bg="#409EFF"
        :value="recordStats.totalCount"
        label="总处理记录"
      />
      <StatCard
        :icon="TrendCharts"
        icon-bg="#67C23A"
        :value="`${recordStats.todayCount}`"
        label="今日处理"
      />
      <StatCard
        :icon="Timer"
        icon-bg="#E6A23C"
        :value="`${recordStats.avgHandleTime}分钟`"
        label="平均处理时间"
      />
      <StatCard
        :icon="SuccessFilled"
        icon-bg="#67C23A"
        :value="`${recordStats.accuracyRate}%`"
        label="处理准确率"
      />
    </div>

    <!-- 质检员绩效统计 -->
    <el-card class="performance-card" style="margin-bottom: 20px;">
      <template #header>
        <div class="card-header">
          <span>质检员绩效统计</span>
          <el-button type="text" @click="refreshPerformance">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      <div class="performance-grid">
        <div
          v-for="performance in performanceList"
          :key="performance.inspectorId"
          class="performance-item"
        >
          <div class="inspector-info">
            <el-avatar :size="40">{{ performance.inspectorName.charAt(0) }}</el-avatar>
            <div class="inspector-details">
              <div class="name">{{ performance.inspectorName }}</div>
              <div class="role">质检员</div>
            </div>
          </div>
          <div class="performance-stats">
            <div class="stat-item">
              <span class="label">今日处理</span>
              <span class="value">{{ performance.todayCount }}</span>
            </div>
            <div class="stat-item">
              <span class="label">本月处理</span>
              <span class="value">{{ performance.monthCount }}</span>
            </div>
            <div class="stat-item">
              <span class="label">准确率</span>
              <span class="value success">{{ performance.accuracyRate }}%</span>
            </div>
            <div class="stat-item">
              <span class="label">平均用时</span>
              <span class="value">{{ performance.avgTime }}分钟</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button
          type="success"
          @click="handleExport"
        >
          <el-icon><Download /></el-icon>
          导出记录
        </el-button>
        <el-button
          type="info"
          @click="handleExportPerformance"
        >
          <el-icon><DataAnalysis /></el-icon>
          导出绩效
        </el-button>
      </div>
      <div class="action-right">
        <el-button
          type="info"
          @click="loadRecordList"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 质检记录列表表格 -->
    <DataTable
      :data="recordList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
    >
      <el-table-column prop="id" label="记录ID" width="100" />
      <el-table-column label="处理时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.handleTime) }}
        </template>
      </el-table-column>
      <el-table-column label="异常信息" width="200">
        <template #default="{ row }">
          <div>异常ID: #{{ row.exceptionId }}</div>
          <div class="text-secondary">{{ getExceptionTypeText(row.exceptionType) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="用户信息" width="150">
        <template #default="{ row }">
          <div>{{ row.userName }}</div>
          <div class="text-secondary">{{ row.userPhone }}</div>
        </template>
      </el-table-column>
      <el-table-column label="设备信息" width="150">
        <template #default="{ row }">
          <div>{{ row.deviceName }}</div>
          <div class="text-secondary">{{ row.deviceCode }}</div>
        </template>
      </el-table-column>
      <el-table-column label="处理结果" width="120">
        <template #default="{ row }">
          <el-tag :type="getResultTag(row.handleResult)">
            {{ getResultText(row.handleResult) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="金额调整" width="120">
        <template #default="{ row }">
          <span v-if="row.adjustmentAmount" :class="getAmountClass(row.handleResult)">
            {{ getAmountPrefix(row.handleResult) }}¥{{ row.adjustmentAmount }}
          </span>
          <span v-else class="text-secondary">-</span>
        </template>
      </el-table-column>
      <el-table-column label="质检员" width="100">
        <template #default="{ row }">
          {{ row.inspectorName }}
        </template>
      </el-table-column>
      <el-table-column label="处理时长" width="100">
        <template #default="{ row }">
          {{ row.handleDuration }}分钟
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button
            type="info"
            size="small"
            @click="handleViewDetail(row)"
          >
            查看详情
          </el-button>
          <el-dropdown @command="(command: string) => handleMoreAction(command, row)">
            <el-button type="text" size="small">
              更多<el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="exception">查看异常</el-dropdown-item>
                <el-dropdown-item command="user">用户详情</el-dropdown-item>
                <el-dropdown-item command="device">设备详情</el-dropdown-item>
                <el-dropdown-item command="timeline">处理时间线</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="质检记录详情"
      width="70%"
    >
      <div v-if="currentRecord" class="record-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录ID">
            {{ currentRecord.id }}
          </el-descriptions-item>
          <el-descriptions-item label="处理时间">
            {{ formatDate(currentRecord.handleTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="异常ID">
            #{{ currentRecord.exceptionId }}
          </el-descriptions-item>
          <el-descriptions-item label="异常类型">
            {{ getExceptionTypeText(currentRecord.exceptionType) }}
          </el-descriptions-item>
          <el-descriptions-item label="用户信息">
            {{ currentRecord.userName }} ({{ currentRecord.userPhone }})
          </el-descriptions-item>
          <el-descriptions-item label="设备信息">
            {{ currentRecord.deviceName }} ({{ currentRecord.deviceCode }})
          </el-descriptions-item>
          <el-descriptions-item label="处理结果">
            <el-tag :type="getResultTag(currentRecord.handleResult)">
              {{ getResultText(currentRecord.handleResult) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="金额调整">
            <span v-if="currentRecord.adjustmentAmount" :class="getAmountClass(currentRecord.handleResult)">
              {{ getAmountPrefix(currentRecord.handleResult) }}¥{{ currentRecord.adjustmentAmount }}
            </span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="质检员">
            {{ currentRecord.inspectorName }}
          </el-descriptions-item>
          <el-descriptions-item label="处理时长">
            {{ currentRecord.handleDuration }}分钟
          </el-descriptions-item>
          <el-descriptions-item label="处理说明" :span="2">
            {{ currentRecord.handleReason || '-' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="currentRecord.remark" label="备注" :span="2">
            {{ currentRecord.remark }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 处理时间线 -->
        <div class="timeline-section" style="margin-top: 20px;">
          <h4>处理时间线</h4>
          <el-timeline>
            <el-timeline-item
              v-for="item in currentRecord.timeline"
              :key="item.id"
              :timestamp="formatDate(item.time)"
              :type="item.type"
            >
              <div class="timeline-content">
                <div class="timeline-title">{{ item.title }}</div>
                <div class="timeline-description">{{ item.description }}</div>
                <div v-if="item.operator" class="timeline-operator">
                  操作人：{{ item.operator }}
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Document,
  TrendCharts,
  Timer,
  SuccessFilled,
  Refresh,
  Download,
  DataAnalysis,
  ArrowDown
} from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import SearchForm from '@/components/SearchForm.vue'
import DataTable from '@/components/DataTable.vue'
import StatCard from '@/components/StatCard.vue'
import { useQualityStore } from '@/stores/quality'
import { formatDate } from '@/utils'

const qualityStore = useQualityStore()

const loading = ref(false)
const detailDialogVisible = ref(false)
const currentRecord = ref<any>(null)

// 搜索表单
const searchForm = reactive({
  inspectorId: '',
  handleResult: '',
  exceptionType: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 记录统计
const recordStats = reactive({
  totalCount: 1256,
  todayCount: 45,
  avgHandleTime: 8.5,
  accuracyRate: 96.8
})

// 质检记录列表
const recordList = ref<any[]>([])

// 质检员选项
const inspectorOptions = ref([
  { id: 1, name: '张质检' },
  { id: 2, name: '李质检' },
  { id: 3, name: '王质检' }
])

// 质检员绩效列表
const performanceList = ref([
  {
    inspectorId: 1,
    inspectorName: '张质检',
    todayCount: 15,
    monthCount: 342,
    accuracyRate: 97.2,
    avgTime: 7.8
  },
  {
    inspectorId: 2,
    inspectorName: '李质检',
    todayCount: 18,
    monthCount: 398,
    accuracyRate: 96.5,
    avgTime: 8.2
  },
  {
    inspectorId: 3,
    inspectorName: '王质检',
    todayCount: 12,
    monthCount: 289,
    accuracyRate: 98.1,
    avgTime: 7.5
  }
])

// 获取异常类型文本
const getExceptionTypeText = (type: string) => {
  switch (type) {
    case 'weight_error':
      return '重量异常'
    case 'classification_error':
      return '分类错误'
    case 'image_mismatch':
      return '图像不符'
    default:
      return '其他'
  }
}

// 获取处理结果标签
const getResultTag = (result: string) => {
  switch (result) {
    case 'deduction':
      return 'danger'
    case 'addition':
      return 'success'
    case 'no_adjustment':
      return 'info'
    default:
      return 'info'
  }
}

// 获取处理结果文本
const getResultText = (result: string) => {
  switch (result) {
    case 'deduction':
      return '扣款'
    case 'addition':
      return '补款'
    case 'no_adjustment':
      return '无需调整'
    default:
      return '未知'
  }
}

// 获取金额样式类
const getAmountClass = (result: string) => {
  switch (result) {
    case 'deduction':
      return 'amount-text negative'
    case 'addition':
      return 'amount-text positive'
    default:
      return 'amount-text'
  }
}

// 获取金额前缀
const getAmountPrefix = (result: string) => {
  switch (result) {
    case 'deduction':
      return '-'
    case 'addition':
      return '+'
    default:
      return ''
  }
}

// 加载质检记录列表
const loadRecordList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    const response = await qualityStore.fetchQualityRecords(params)
    recordList.value = response.list
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('加载质检记录失败')
  } finally {
    loading.value = false
  }
}

// 刷新绩效数据
const refreshPerformance = () => {
  ElMessage.success('绩效数据已刷新')
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadRecordList()
}

// 重置处理
const handleReset = () => {
  pagination.page = 1
  loadRecordList()
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.page = page
  loadRecordList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadRecordList()
}

// 查看详情
const handleViewDetail = (row: any) => {
  // 模拟添加时间线数据
  row.timeline = [
    {
      id: 1,
      time: row.handleTime,
      type: 'success',
      title: '质检处理完成',
      description: `处理结果：${getResultText(row.handleResult)}`,
      operator: row.inspectorName
    },
    {
      id: 2,
      time: new Date(new Date(row.handleTime).getTime() - 5 * 60 * 1000).toISOString(),
      type: 'primary',
      title: '开始质检处理',
      description: '质检员开始处理异常投递',
      operator: row.inspectorName
    },
    {
      id: 3,
      time: new Date(new Date(row.handleTime).getTime() - 10 * 60 * 1000).toISOString(),
      type: 'info',
      title: '异常检测',
      description: '系统检测到异常投递',
      operator: '系统'
    }
  ]
  
  currentRecord.value = row
  detailDialogVisible.value = true
}

// 导出记录
const handleExport = () => {
  ElMessage.info('导出记录功能开发中...')
}

// 导出绩效
const handleExportPerformance = () => {
  ElMessage.info('导出绩效功能开发中...')
}

// 更多操作
const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'exception':
      ElMessage.info('查看异常功能开发中...')
      break
    case 'user':
      ElMessage.info('用户详情功能开发中...')
      break
    case 'device':
      ElMessage.info('设备详情功能开发中...')
      break
    case 'timeline':
      handleViewDetail(row)
      break
  }
}

onMounted(() => {
  loadRecordList()
})
</script>

<style lang="scss" scoped>
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.performance-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.performance-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.performance-item {
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;

  .inspector-info {
    display: flex;
    align-items: center;
    margin-bottom: 16px;

    .inspector-details {
      margin-left: 12px;

      .name {
        font-weight: 600;
        font-size: 14px;
      }

      .role {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .performance-stats {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;

    .stat-item {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .label {
        font-size: 12px;
        color: #909399;
      }

      .value {
        font-weight: 600;
        font-size: 14px;

        &.success {
          color: #67c23a;
        }
      }
    }
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .action-left,
  .action-right {
    display: flex;
    gap: 12px;
  }
}

.text-secondary {
  font-size: 12px;
  color: #909399;
}

.amount-text {
  font-weight: 600;

  &.positive {
    color: #67c23a;
  }

  &.negative {
    color: #f56c6c;
  }
}

.record-detail {
  .timeline-section {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }
  }

  .timeline-content {
    .timeline-title {
      font-weight: 600;
      margin-bottom: 4px;
    }

    .timeline-description {
      color: #606266;
      margin-bottom: 4px;
    }

    .timeline-operator {
      font-size: 12px;
      color: #909399;
    }
  }
}

@media (max-width: 768px) {
  .stats-grid,
  .performance-grid {
    grid-template-columns: 1fr;
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left,
    .action-right {
      justify-content: center;
    }
  }

  .performance-item {
    .performance-stats {
      grid-template-columns: 1fr;
    }
  }
}
</style>